package iot.wlink.network.protocols.mqtt;

import iot.wlink.network.protocols.NetworkComponent;
import iot.wlink.utils.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.codec.ByteBufferAllocator;
import net.dreamlu.iot.mqtt.codec.ByteBufferUtil;
import net.dreamlu.iot.mqtt.core.server.MqttServer;
import net.dreamlu.iot.mqtt.core.server.MqttServerCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author : willian fu
 * @date : 2021/8/19
 */
@Slf4j
@Component
public class MqttIotServerComponent implements NetworkComponent {

    private int port;

    private MqttServer mqttServer;

    private MqttServerCreator serverCreator;

    @Autowired
    private MqttConnectStatusListener statusListener;

    @Autowired
    private MqttDeviceAuthenticationHandler authenticationHandler;

    @Autowired
    private MqttDeviceManager manager;

    @Autowired
    private MqttMessageListener messageListener;

    @Override
    public void initialize() {
        serverCreator = MqttServer.create()
                // 默认：127.0.0.1
                .ip("127.0.0.1")
                // 默认：1883 1884
                .port(1883)
                .webPort(1884)
                .websocketEnable(true)
                // 默认为： 8092（mqtt 默认最大消息大小），为了降低内存可以减小小此参数，如果消息过大 t-io 会尝试解析多次（建议根据实际业务情况而定）
                .readBufferSize(512)
                // 最大包体长度，如果包体过大需要设置此参数，默认为： 8092
                .maxBytesInMessage(1024 * 100)
                // 自定义认证
                .authHandler(authenticationHandler)
                //上下线状态监听
                .connectStatusListener(statusListener)
                // 消息监听
                .messageListener(messageListener)
                // 堆内存和堆外内存选择，默认：堆内存
                .bufferAllocator(ByteBufferAllocator.HEAP)
                // 心跳超时时间，默认：120s
                .heartbeatTimeout(120_1000L);
    }

    @Override
    public void stater() {
        mqttServer = serverCreator.start();
        manager.setServer(mqttServer);
    }

}
